package handles

import (
	"encoding/json"
	"game-master/cache"
	"game-master/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")

	if name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Game{

		Name: name,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	var game models.Game
	id := strconv.Itoa(int(data.ID))
	redis_key := "game" + id
	models.DB.Where("id=?", data.ID).First(&game)
	jsonData, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	var game []models.Game

	redis_key := "game_list"
	models.DB.Find(&game)
	jsonData, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": game,
	})
	return
}

func Find(c *gin.Context) {

	id := c.Query("id")
	var game models.Game

	redis_key := "game_find" + id
	models.DB.Where("id=?", id).Find(&game)
	jsonData, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": game,
	})
	return
}
